import React, { useEffect, useState } from 'react'
import { Menu } from "antd"

import config from "../config/menuConfig"
import { useDispatch } from "react-redux"
import { MenuActionPush } from "../redux/actions/MenuAction"



export default function MyMenu({ theme }) {
    const [userInfo, setUserInfo] = useState({ role: {} })
    useEffect(() => {
        const info = JSON.parse(localStorage.userInfo || "{}")
        setUserInfo(info)
    }, [])
    const dispatch = useDispatch()
    //登录成功拿到权限(菜单),本地有所有菜单
    //登录后拿到菜单 ["/home/","/home/user","/home/salary"]
    //本地构造的完整菜单 [{name:"",key,""}]

    /**
     * 两个数组找到匹配的结果.
     * @param {*} array 所有菜单
     * @param {*} news 产生的菜单
     */
    const deepMenus = (array, news = []) => {
        //登录成功后，本地存储的menus
        const { menus = [] } = userInfo.role
        for (const menu of array) {
            if (!menu.children) {
                if (menus.includes(menu.key)) {
                    news.push(menu)
                }
            } else {
                let node = { ...menu, children: [] }
                deepMenus(menu.children, node.children)
                if (node.children.length != 0) {
                    news.push(node)
                }
            }
        }
        return news
    }
    const checkedMenu = ({ item, key, keyPath, domEvent }) => {
        console.log(item);
        console.log(key);
        console.log(keyPath);
        const title = domEvent.target.innerText;
        let menu = {
            title,
            path: key,
            status: true
        }
        dispatch(MenuActionPush(menu))

    }
    return (
        <>
            <Menu
                theme={theme}
                mode="inline"
                defaultSelectedKeys={['/home/']}
                defaultOpenKeys={["/home/product"]}
                items={deepMenus(config)}
                onClick={checkedMenu}
            />
            {/* <Menu
                theme={theme}
                mode="inline"
                defaultSelectedKeys={['/home/']}
                defaultOpenKeys={["/home/product"]}

            >
                {array.map(item=>{
                    if(item.children){
                        return <SubMenu></SubMenu>
                    }else{
                        return <Menu.Item></Menu.Item>
                    }
                })}
                <Menu.Item></Menu.Item>
                <SubMenu></SubMenu>
            </Menu> */}
        </>
    )
}
